package cn.exrick.xboot.quartz.jobs;

import cn.exrick.xboot.common.constant.CommonConstant;
import cn.exrick.xboot.common.exception.XbootException;
import cn.exrick.xboot.common.utils.ResultUtil;
import cn.exrick.xboot.common.utils.jiuqi.utils.CommonUtil;
import cn.exrick.xboot.modules.backlogOrFullList.service.IbacklogOrFullListService;
import cn.exrick.xboot.modules.base.entity.QuartzJob;
import cn.exrick.xboot.modules.base.service.QuartzJobService;
import cn.exrick.xboot.quartz.jobs.distributedLock.entity.Lock;
import cn.exrick.xboot.quartz.jobs.distributedLock.utils.DistributedLockHandler;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: njp
 * @Date: 2020/07/07/17:32
 * @Description:
 */
@Slf4j
@DisallowConcurrentExecution
public class ManualBackLogInitJob implements Job {
    @Autowired
    private DistributedLockHandler distributedLockHandler;
    @Autowired
    private IbacklogOrFullListService ibacklogOrFullListService;
    @Autowired
    private QuartzJobService quartzJobService;
    @Autowired
    private Scheduler scheduler;
    /**
     * 若参数变量名修改 QuartzJobController中也需对应修改
     */
    private String parameter;
    public void setParameter(String parameter) {
        this.parameter = parameter;
    }
    //private String packageName = ManualBackLogInitJob.class.getPackage().getName();
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.info("定时测试"+this.parameter);
        String nowTime = CommonUtil.getTime().toString();
        Lock lock = new Lock("redisLock:backlogInit", nowTime);
        long timeout = 20 * 1000L;
        //过期时间60秒*6
        long lockExpireTime = 60 * 6 * 1000L;
        if (distributedLockHandler.individualityTryLock(lock, timeout, lockExpireTime)) {
            try {
                synchronized ("") {
                    this.stopJob();
                    ibacklogOrFullListService.backlogInitByCall();
                    distributedLockHandler.releaseLock(lock);
                }
            } catch(Exception e){
                distributedLockHandler.releaseLock(lock);
                e.printStackTrace();
            }
        }

    }

    public void stopJob(){
        List<QuartzJob> list = quartzJobService.findByJobClassName(this.parameter);
        try{
            if(list!=null&&list.size()>0){
                QuartzJob  job=list.get(0);
                scheduler.pauseJob(JobKey.jobKey(job.getJobClassName()));
                job.setStatus(CommonConstant.STATUS_DISABLE);
                quartzJobService.update(job);
            }
        } catch (SchedulerException e) {
            throw new XbootException("暂停定时任务失败");
        }
    }

}
